import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../../HomePage/NewsItem.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../widgets/AppColors.dart';

class FirmPage extends StatefulWidget {
  const FirmPage({super.key});

  @override
  State<FirmPage> createState() => _FirmPageState();
}

class _FirmPageState extends State<FirmPage>
    with SingleTickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();
  List<dynamic> firmList = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['data'] != null) {
        setState(() {
          firmList = (result['data'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    try {
      final response = await _networkService.get('/system/dept/deptList');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('deptList Failed to load data');
      }
    } catch (e) {
      print('deptList Error in _fetchData: $e');
      rethrow;
    }
  }

  Future<void> _loadChooseData(int deptID) async {
    try {
      final result = await _chooseFetchData(deptID);
      if (result['code'] == 200 && result['data'] != null) {
        LocalStorage.setstr('deptName', result['data']['deptName']);
        LocalStorage.setstr('childDeptName', result['data']['childDeptName']);
        TDToast.showText('切换成功！', context: context);
        Navigator.pop(context);
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadChooseData: $e');
    }
  }

  Future<Map<String, dynamic>> _chooseFetchData(int deptID) async {
    try {
      final response =
          await _networkService.get('/system/dept/chooseDept?deptId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('chooseDept Failed to load data');
      }
    } catch (e) {
      print('chooseDept Error in _fetchData: $e');
      rethrow;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('企业设置'),
        foregroundColor: AppColors.textPrimary,
        backgroundColor: Colors.transparent,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          Align(
            alignment: Alignment.centerLeft, // 添加对齐方式
            child: Text(
              '   你的账号可查看${firmList.length}个企业',
              style: TextStyle(fontSize: 15, color: AppColors.textPrimary),
            ),
          ),
          const SizedBox(height: 10),
          // 列表
          SizedBox(
            height: MediaQuery.of(context).size.height - 280,
            child: ListView.builder(
              itemCount: firmList.length, // 数据条数
              shrinkWrap: true, // 适应内容高度
              itemBuilder: (context, index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 0.0), // 设置行间距为1
                  child: GestureDetector(
                    onTap: () {
                      if (firmList[index]['businessId'] == 0) {
                        showGeneralDialog(
                          context: context,
                          pageBuilder: (BuildContext buildContext,
                              Animation<double> animation,
                              Animation<double> secondaryAnimation) {
                            return TDAlertDialog(
                              title: '提示',
                              content: '确定要切换公司吗？',
                              leftBtnAction: () => {Navigator.pop(context)},
                              rightBtnAction: () => {
                                Navigator.pop(context),
                                _loadChooseData(firmList[index]['deptId'])
                              },
                            );
                          },
                        );
                      }
                    },
                    child: FirmItem(data: firmList[index]),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class FirmItem extends StatelessWidget {
  final Map<String, dynamic> data;
  const FirmItem({super.key, required this.data});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 16, bottom: 16),
      margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.0), // 圆角边框
        color: AppColors.cardColor, // 背景色
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              const SizedBox(width: 16),
              Image(
                  image: AssetImage(data['businessId'] == 1
                      ? 'assets/images/setting/firm_sel.png'
                      : 'assets/images/setting/firm_nol.png')),
              const SizedBox(width: 10),
              Text(
                data['deptName'] ?? '',
                style: TextStyle(fontSize: 15, color: AppColors.textPrimary),
              ),
            ],
          ),
          Row(children: [
            Text(
              data['businessId'] == 1 ? '已选择' : '选择',
              style: TextStyle(
                  fontSize: 15,
                  color: data['businessId'] == 0
                      ? Color(0xFF4E5969)
                      : Color(0xFF2AB6F7)),
            ),
            const SizedBox(width: 16),
          ])
        ],
      ),
    );
  }
}
